package org.ourgrid.discoveryservice.business.requester;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAO;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAOFactory;
import org.ourgrid.discoveryservice.request.DSIsUpRequestTO;
import org.ourgrid.discoveryservice.response.DSGetDiscoveryServicesResponseTO;
import org.ourgrid.discoveryservice.response.DSHereAreDiscoveryServicesResponseTO;
/**
 * Requirement 511
 */
public class DSIsUpRequester implements RequesterIF<DSIsUpRequestTO>{

	public List<IResponseTO> execute(DSIsUpRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		DiscoveryServiceDAO discoveryServiceDAO = DiscoveryServiceDAOFactory.getInstance().getDiscoveryServiceDAO();
		
		List<String> oldDiscoveryServicesAddresses = discoveryServiceDAO.getDiscoveryServicesAddresses();
		
		boolean modified = discoveryServiceDAO.addDiscoveryService(request.getDsAddress());
		
		DSGetDiscoveryServicesResponseTO getDSResponseTO = new DSGetDiscoveryServicesResponseTO();
		getDSResponseTO.setDsAddress(request.getDsAddress());
		
		responses.add(getDSResponseTO);
		
		List<String> updatedDiscoveryServicesAddresses = discoveryServiceDAO.getDiscoveryServicesAddresses();
		
		if (modified){
			for (String address : updatedDiscoveryServicesAddresses) {
				if (address.equals(request.getDsAddress()) || address.equals(request.getMyAddress())) {
					continue;
				}

				DSHereAreDiscoveryServicesResponseTO to = new DSHereAreDiscoveryServicesResponseTO();
				to.setDiscoveryServices(updatedDiscoveryServicesAddresses);
				to.setStubAddress(address);
				
				responses.add(to);
				
				responses.add(new LoggerResponseTO("DiscoveryServiceNotificationController.dsIsUp() \n" +
						"Table before: "+ oldDiscoveryServicesAddresses +
						"\nTable after: " + updatedDiscoveryServicesAddresses, LoggerResponseTO.INFO));
			}
		}
		
		return responses;
	}
	
}
